package main

//manggo
import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
	global "userapi/Global" //go.mode里定义的根目录名+包文件夹名引入第三方包
)

type User struct {
	Name     string `gorm:"primaryKey"` //设置主键
	Password string
	Role     int
}

// 返回数据结构
type Message struct {
	Type    string `json:"type"`
	Reslut  string `json:"reslut"`
	Message string `json:"message"`
	Data    string `json:"data"`
}

// 接受数据结构
type ReceiveMessage struct {
	Cmdtype  string `json:"cmdtype"`
	Username string `json:"username"`
}

var configFileName = "config.ini"
var lastRequestTime time.Time

// http实现
func ActionUser(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		result := ResponsetoRequset(r.URL.Query().Get("t"), r.URL.Query().Get("u"), r.URL.Query().Get("p"))
		ResponseWithOrigin(w, http.StatusOK, result)
	}
}

func ResponsetoRequset(cmdtype string, username string, password string) []byte {
	var message Message
	message.Type = cmdtype
	message.Reslut = "true"
	message.Message = username
	staticCmdType := []string{"登录", "sqlite注册", "sqlite删除", "芒果注册", "获取用户列表", "获取用户列表sqlite"}
	//间隔给异步cmd执行时间
	if time.Since(lastRequestTime) < 50000000 {
		message.Message = "请求频率过快,限制最低间隔50毫秒"
	} else if !IsContain(staticCmdType, cmdtype) {
		message.Message = "t需传入" + ConnectArrayString(staticCmdType)
	} else if cmdtype == "登录" {
		collection := global.GvaMongo.Database("users").Collection("users_all")
		if Checkuser(context.TODO(), collection, username, password, true) {
			message.Reslut = "true"
			message.Message = "登录成功"
		} else {
			message.Reslut = "false"
			message.Message = "登录失败"
		}
	} else if cmdtype == "sqlite注册" {
		message.Data = InsertOneSqlite(global.GvaSqlite, username, password)
		if message.Data == "插入成功" {
			message.Reslut = "true"
		} else {
			message.Reslut = "false"
		}

	} else if cmdtype == "sqlite删除" {
		message.Data = DelteOneSqlite(global.GvaSqlite, username)
		if message.Data == "删除成功" {
			message.Reslut = "true"
		} else {
			message.Reslut = "false"
		}

	} else if cmdtype == "芒果注册" {
		if message.Data == "插入成功" {
			message.Reslut = "true"
		} else {
			message.Reslut = "false"
		}
		collection := global.GvaMongo.Database("users").Collection("users_all")

		if create(context.TODO(), collection, username, password) {
			message.Reslut = "true"
			message.Message = "注册成功"
		} else {
			message.Reslut = "false"
			message.Message = "注册失败"

		}
	} else if cmdtype == "获取用户列表" {
		collection := global.GvaMongo.Database("users").Collection("users_all")
		userlist := findallusera(context.TODO(), collection)
		data, _ := json.Marshal(userlist)
		message.Data = string(data)

	} else if cmdtype == "获取用户列表sqlite" {
		userlist, _ := GetUsers(global.GvaSqlite)
		data, _ := json.Marshal(userlist)
		message.Data = string(data)

	} else {
		message.Message = "未知错误！"

	}
	lastRequestTime = time.Now()
	result, err := json.Marshal(&message)
	if err != nil {
		fmt.Println(err)
		message.Message = err.Error()
		log.Println(err.Error())
	}

	log.SetPrefix("【http响应日志】")
	log.Println(string(result))
	return result

}
func ResponseWithOrigin(w http.ResponseWriter, code int, json []byte) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.WriteHeader(code)
	w.Write(json)
}

func main() {
	initmysql()
	// 初始化sqlite数据库连接
	db, err := InitDB()
	if err != nil {
		panic(err)
	}
	global.GvaSqlite = db
	lastRequestTime = time.Now()
	log.SetPrefix("【开始运行】")
	log.Println("已启动监听端口:82 url:/api/User")
	port := "82"
	CreateDefaultConfig()
	global.GvaMongo = ConnectMongoDb()
	if global.GvaMongo == nil {
		log.Fatal("芒果未连接")
	}
	configMap := InitConfig("./" + configFileName)
	port = configMap["端口号"]
	http.HandleFunc("/api/User", ActionUser)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.SetPrefix(err.Error())
	}
}
